﻿var iconcount=0;
function handleIQ(aIQ) {
  document.getElementById('iResp').innerHTML += 
    "<div class='msg'>IN (raw): " +aIQ.xml().htmlEnc() + '</div>';
  document.getElementById('iResp').lastChild.scrollIntoView();
}

function handleMessage(aJSJaCPacket) {
  var html = '';
  html += '<div class="msg"><b>'+aJSJaCPacket.getFromJID().getResource() +':</b><br/>';
  html += aJSJaCPacket.getBody()+ '</div>';
  document.getElementById('iResp').innerHTML += html;
  document.getElementById('iResp').lastChild.scrollIntoView();
}

function handlePresence(aJSJaCPacket) {
  var html = '<div class="msg">';
  if (!aJSJaCPacket.getType() && !aJSJaCPacket.getShow()) 
    html += '<b>'+aJSJaCPacket.getFromJID()+' has become available.</b>';
  else {
    html += '<b>'+aJSJaCPacket.getFromJID()+' has set his presence to ';
    if (aJSJaCPacket.getType())
      html += aJSJaCPacket.getType() + '.</b>';
    else
      html += aJSJaCPacket.getShow() + '.</b>';
    if (aJSJaCPacket.getStatus())
      html += ' ('+aJSJaCPacket.getStatus().htmlEnc()+')';
  }
  html += '</div>';

  document.getElementById('iResp').innerHTML += html;
  document.getElementById('iResp').lastChild.scrollIntoView();
}

function handleError(e) {
  document.getElementById('err').innerHTML = "An error occured:<br />"+ 
    ("Code: "+e.getAttribute('code')+"\nType: "+e.getAttribute('type')+
    "\nCondition: "+e.firstChild.nodeName).htmlEnc(); 
  //document.getElementById('login_pane').style.display = '';
  //document.getElementById('main_pane').style.display = 'none';
}

function handleStatusChanged(status) {
  oDbg.log("status changed: "+status);
}

function handleConnected() {
  document.getElementById('login_pane').style.display = 'none';
  document.getElementById('main_pane').style.display = '';
  document.getElementById('err').innerHTML = '';
}

function handleDisconnected() {
  document.getElementById('login_pane').style.display = '';
  document.getElementById('main_pane').style.display = 'none';
}


function doLogin(aForm) {
  document.getElementById('err').innerHTML = ''; // reset

  try {
       var bkg=chrome.extension.getBackgroundPage();
	   if(bkg.connected()){
	        document.getElementById('login_pane').style.display = 'none';
            document.getElementById('main_pane').style.display = '';
            document.getElementById('err').innerHTML = '';
	   }
	   var ret=bkg.doLogin(aForm);
	   return false;
  } catch (e) {
      document.getElementById('err').innerHTML = e.toString();
  } finally {
      return false;
  }

}

function sendMsg(aForm) {
  try{
      var bkg=chrome.extension.getBackgroundPage();
	  var ret=bkg.sendMsg(aForm);
	  return false;
  } catch (e) {
    html = "<div class='msg error''>Error: "+e.message+"</div>"; 
    document.getElementById('iResp').innerHTML += html;
    document.getElementById('iResp').lastChild.scrollIntoView();
    return false;
  }
}

function quit() {
    try{
      var bkg=chrome.extension.getBackgroundPage();
	  var ret=bkg.quit();
  } catch (e) {
      
  }
  document.getElementById('login_pane').style.display = '';
  document.getElementById('main_pane').style.display = 'none';
}

function dispEvents()
{
    try{
	    var bkg=chrome.extension.getBackgroundPage();
        var eventQ=bkg.EvenQueue;
	    while(eventQ.length>0){
	        event=eventQ.shift();
	    	if(typeof event.body=='undefined')
	    	    eval(event.handler)();
	        else
	    	    eval(event.handler)(event.body);
	    }
		if(bkg.ActiveSession!='' && 'undefined' != typeof bkg.MsgSession[bkg.ActiveSession]){
		    while(bkg.MsgSession[bkg.ActiveSession].length>0){
			    var Msg=bkg.MsgSession[bkg.ActiveSession].shift();
				handleMessage(Msg);
			}
		}
	}
	catch(e){}
}

function switchPane(){
    var bkg=chrome.extension.getBackgroundPage();
    var url=$(this).attr('title');
	var roomId=bkg.joinedRooms[url]+'@conference.'+bkg.getDomain();
	bkg.ActiveSession=url;
	if('undefined' != typeof bkg.MsgSession[url]){
	    if(bkg.Context[bkg.joinedRooms[url]]){
	        document.getElementById('iResp').innerHTML=bkg.Context[bkg.joinedRooms[url]];
		}
	    while(bkg.MsgSession[url].length>0){
		    var Msg=bkg.MsgSession[url].shift();
			handleMessage(Msg);
		}
	}
	$('#groupname').html($(this).html());
    $("input[name='sendTo']").attr('value',roomId);
    $('#list_pane').hide( 'slide', {}, 20, function(){
	    $('#sendmsg_pane').show( 'slide', {}, 20,function(){
		    if(document.getElementById('iResp').lastChild){
		        document.getElementById('iResp').lastChild.scrollIntoView();
			}
		});
	});
	if(document.getElementById('iResp').lastChild){
	    document.getElementById('iResp').lastChild.scrollIntoView();
	}
}

function updateGroupListUI(id, url){
    var bkg=chrome.extension.getBackgroundPage();
	
	if(bkg.MsgSession[url] && bkg.MsgSession[url].length>0){
	    document.getElementById(id).innerHTML="<img src='submsg.gif'>";
	}
	else{
	    document.getElementById(id).innerHTML="";
	}
}

function updataGroupList()
{
    try{
        var bkg=chrome.extension.getBackgroundPage();
		if(!bkg.connected())
		    return;
	    var itemnum=0;
	    document.getElementById('iGroupList').innerHTML='';
	    for(key in bkg.joinedRooms){
	        var url=key;
			var urlinfo=bkg.tabUrlManager[url];
			var favicon=urlinfo.favIconUrl;
			var title=urlinfo.title;
	    	var html = "<div class='groupitem'>";
			html+="<span><img src='"+favicon+"'></span>";
			html+="<span id='groupitem"+itemnum+"' title='"+url+"'>"+title+"</span>";
			html+="<span id='itemmsg"+itemnum+"'></span>";
			html+="</div>";
            document.getElementById('iGroupList').innerHTML += html;
            document.getElementById('iGroupList').lastChild.scrollIntoView();
	    	updateGroupListUI('itemmsg'+itemnum,url);
	    	itemnum++;
	    }
		for(var i=0;i<itemnum;i++){
		    $('#groupitem'+i).click(switchPane);
		}
		var itemnum1=0;
		document.getElementById('iHistoryList').innerHTML='';
		var history=bkg.GetHistory();
		if(history){
		    for(key in history){
			    var idx=itemnum+itemnum1;
	            var item=history[key];
			    var url=item.url;
			    var favicon=item.favIconUrl;
			    var title=item.title;
	    	    var html = "<div class='groupitem'>";
			    html+="<span><img src='"+favicon+"'></span>";
			    html+="<span id='groupitem"+idx+"' title='"+url+"'>"+title+"</span>";
			    html+="</div>";
                document.getElementById('iHistoryList').innerHTML += html;
                document.getElementById('iHistoryList').lastChild.scrollIntoView();
	        }
		}
		for(var i=0;i<itemnum1;i++){
		    var idx=i+itemnum;
		    $('#groupitem'+idx).click(switchPane);
		}
	}
	catch(e){}
}

function init() {
    chrome.extension.sendRequest({cmd: "connected",data:"0"}, function(response) {
        if(response.ret==true){
		    document.getElementById('login_pane').style.display = 'none';
			document.getElementById('main_pane').style.display = '';
			document.getElementById('err').innerHTML = '';
		}
		else{
		    chrome.extension.sendRequest({cmd: "connectresume",data:"0"}, function(response) {
			    if(response.ret==false){
				    chrome.extension.sendRequest({cmd: "reconnect",data:"0"}, function(response) {
					    if(response.ret==false){
						    document.getElementById('login_pane').style.display = '';
                            document.getElementById('main_pane').style.display = 'none';
				            document.getElementById('err').innerHTML = '未登录';
						}
					});
				}
			});
		}
    });
	try{
	    updataGroupList();
	    setInterval("onOneSecondClock()",1000);
	}
	catch(e){}

}

function onOneSecondClock() {
    dispEvents();
	updataGroupList();
}

onerror = function(e) { 
  document.getElementById('err').innerHTML = e; 

  document.getElementById('login_pane').style.display = '';
  document.getElementById('main_pane').style.display = 'none';
  return false; 
};

onunload = function() {
    var bkg=chrome.extension.getBackgroundPage();
	var to=$("input[name='sendTo']").attr('value');
	var roomid=to.split('@');
    bkg.ActiveSession='';
	bkg.Context[roomid[0]]=document.getElementById('iResp').innerHTML;
};

/* Creates a new image from a given source */
function createImage(source) {
   var pastedImage = new Image();
   pastedImage.onload = function() {
      // You now have the image!
   }
   pastedImage.src = source;
   return pastedImage;
}
function pastemsg(event){
    var items=event.clipboardData.items;
	if(items){
	    for(var i=0;i<items.length;i++){
		    if (items[i].type.indexOf("image") !== -1) {
               // We need to represent the image as a file,
               var blob = items[i].getAsFile();
               // and use a URL or webkitURL (whichever is available to the browser)
               // to create a temporary URL to the object
               var URLObj = window.URL || window.webkitURL;
               var source = URLObj.createObjectURL(blob);
 
               // The URL can then be used as the source of an image
               var img=createImage(source);
			   var doc=document.getElementById('msgArea').contentDocument;
			   doc.body.appendChild(img);
			   //$('#msgArea').append(img);
			}
		}
	}
}
function loadmsgarea(){
    var doc=document.getElementById('msgArea').contentDocument;
	doc.designMode="on";
	doc.onpaste=pastemsg;
}

function thirdlogin(){
    chrome.windows.create({'url': 'https://oauth.taobao.com/authorize?response_type=code&client_id=12650812&redirect_uri=http://ec2-174-129-162-239.compute-1.amazonaws.com/thirdlogin.php&scope=item&state=taobao_1',type: "popup", "height":600,"width":600}, function(window) {
    });
}
$(function(){
    $('#list_pane').tabs();
    $('#bklist_pane').click(function(){
        var bkg=chrome.extension.getBackgroundPage();
	    var to=$("input[name='sendTo']").attr('value');
	    var roomid=to.split('@');
        bkg.ActiveSession='';
	    bkg.Context[roomid[0]]=document.getElementById('iResp').innerHTML;
        $('#sendmsg_pane').hide( 'slide', {}, 20, function(){
	        $('#list_pane').show( 'slide', {}, 20,function(){
		    });
	    });
    });
	init();
});